package com.curvebreakers.wheresmystuff.activities;

import com.curvebreakers.wheresmystuff.R;
import com.curvebreakers.wheresmystuff.model.*;

import android.os.*;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.*;
import android.widget.*;

public class LoginFragment extends Fragment implements DBResultListener {
    
    private ProgressDialog progressDialog;
    
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_login, container, false);
		
		final EditText emailEdit = (EditText) view.findViewById(R.id.loginEmail);
		final EditText passwordEdit = (EditText) view.findViewById(R.id.loginPassword);
	    	    
	    final Button button = (Button) view.findViewById(R.id.loginSubmitButton);
        button.setOnClickListener(new View.OnClickListener() {           
	        public void onClick(View v) {              
	        	
	        	String email = emailEdit.getText().toString();
	            String password = passwordEdit.getText().toString();
	          
	            progressDialog = new ProgressDialog(getActivity(), ProgressDialog.THEME_TRADITIONAL);
	            progressDialog.setTitle("Validating login...");
	            progressDialog.setMessage("Please Wait");
	            progressDialog.show();
	            DatabaseModel.authenticate(email, password, LoginFragment.this);
	        }
        });  
        return view;
	}

	@Override
	public void onDBResultReceived(Object obj) {
		progressDialog.dismiss();
		Session.getSession().login((User)obj);
		Intent goToNextActivity = new Intent(getActivity(), HomeActivity.class);
		goToNextActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(goToNextActivity);
	}

	@Override
	public void onDBRequestFailure(String message) {
		progressDialog.dismiss();
		Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
	}

}
